/**第92题*/
//反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 
//
// 说明: 
//1 ≤ m ≤ n ≤ 链表长度。 
//
// 示例: 
//
// 输入: 1->2->3->4->5->NULL, m = 2, n = 4
//输出: 1->4->3->2->5->NULL 
// Related Topics 链表 
// 👍 627 👎 0

package tree.leetcode.editor.cn;

import com.dq.node.List;
import com.dq.node.ListNode;

public class ReverseLinkedListIi {
    public static void main(String[] args) {
        Solution solution = new ReverseLinkedListIi().new Solution();
        ListNode head = List.newList(new int[]{1,2,3,4,5,6,7,8,9});
        List.showList(head);
        head = solution.reverseListMN(head,2,5);
        List.showList(head);

    }
        //leetcode submit region begin(Prohibit modification and deletion)
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {

            return reverseListMN(head, m, n);
        }
        // 反转链表
        public ListNode reverseList(ListNode head){
            if(head==null||head.next==null) return head;
            ListNode last = reverseList(head.next);
            //反转
            head.next.next = head;
            head.next = null;
            return last;
        }
        // 反转链表的前N个
        public ListNode reverseListN(ListNode head, int n){
            if(n==1||head.next==null) return head;
            ListNode last = reverseListN(head.next, n-1);
            //记录下 之后 开头要连接的地方
            ListNode successor = head.next.next;
            head.next.next = head;
            head.next = successor;
            return last;
        }
        // 反转链表的m-n个
        public ListNode reverseListMN(ListNode head, int m,int n){
            if(n==1||head.next==null) return head;
            ListNode last = reverseListMN(head.next, m-1, n-1);
            if (m<=1){
                ListNode successor = head.next.next;
                head.next.next = head;
                head.next = successor;
                return last;
            }
            head.next = last;
            return head;
        }
        // 反转链表的m-n个
        public ListNode reverseListMN2(ListNode head, int m,int n){
            if(m==1){
                return reverseListN(head, n);
            }
            if(head.next==null) return head;
            head.next = reverseListMN2(head.next,m-1, n-1);

            return head;
        }




    }
//leetcode submit region end(Prohibit modification and deletion)

}